package com.mk.magic_c.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/10/3 12:52 上午
 * @desc
 */
@Controller
@Slf4j
public class KaptchaController {

    @Autowired
    private Producer kaptchaProducer;

    @GetMapping("/kaptcha")
    public void kaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        // 将验证码存入 session
        session.setAttribute("kaptcha_code", text);
        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            log.error("响应验证码失败 -> " + e.getMessage());
        }
    }
}
